<template>
  <div>
    <slot></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </div>
</template>
<script lang='ts'>
import { defineComponent, onUnmounted } from "vue";
import mitt from "mitt";

// 添加一个侦听器，并导出
export const emitter = mitt();

type validateFunc = () => boolean;
export default defineComponent({
  name: "ValidateForm",
  components: {},
  emits: ["form-submit"],
  setup(props, context) {
    // 将传过来的？？？
    let funcArr: validateFunc[] = [];
    // 点击事件and发送事件不要搞混了
    const submitForm = () => {
      const result = funcArr.map((fun) => fun());
      context.emit("form-submit", result);
    };
    const callback = (func: any) => {
      funcArr.push(func);
    };
    emitter.on("form-item-created", callback);

    // 不用的时候要取消侦听
    onUnmounted(() => {
      emitter.off("form-item-created", callback);
      funcArr = [];
    });
    return {
      submitForm,
    };
  },
});
</script>
<style scoped>
</style>